package com.gz.moreaseManager.modules.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.gz.moreaseManager.config.SelfUserDetails;
import com.gz.moreaseManager.core.base.Constants;
import com.gz.moreaseManager.core.modal.AjaxResult;
import com.gz.moreaseManager.core.modal.HttpCode;
import com.gz.moreaseManager.core.modal.PageResult;
import com.gz.moreaseManager.modules.entity.Banner;
import com.gz.moreaseManager.modules.entity.Content;
import com.gz.moreaseManager.modules.service.IContentService;
import com.gz.moreaseManager.modules.service.IMenuWebService;
import com.gz.moreaseManager.utils.DateUtil;
import com.gz.moreaseManager.utils.UtilTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import com.gz.moreaseManager.core.base.BaseController;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;
import java.util.Map;

/**
 * <p>
 * 合作内容信息 前端控制器
 * </p>
 *
 * @author wike
 * @since 2019-02-26
 */
@RestController
@RequestMapping("/content")
public class ContentController extends BaseController {

    @Autowired
    private IContentService contentService;
    @Autowired
    private IMenuWebService menuWebService;

    @RequestMapping("list")
    public ModelAndView list(){
        return new ModelAndView("modules/content/list");
    }

    @GetMapping("add")
    public ModelAndView add(){
        return new ModelAndView("modules/content/add");
    }

    @GetMapping("update")
    public ModelAndView update(Integer id){
        Content content = contentService.selectById( id );
        ModelAndView module = new ModelAndView("modules/content/update");
        module.addObject("content",content);
        return module;
    }

    /**
     * 内衣保养页面
     * @return
     */
    @GetMapping("maintain")
    public ModelAndView maintian(){
        Wrapper query = new EntityWrapper();
        query.eq("type","99");
        Content content = contentService.selectOne(query);
        ModelAndView module = new ModelAndView("modules/content/maintain");
        module.addObject("content",content);
        return module;
    }

    @GetMapping("listPage")
    public PageResult<Content> findPageLsit(String name, Integer type,
                                            @DateTimeFormat(pattern = "yyyy-MM-dd")Date startDate,
                                            @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
                                            Integer pageNum, Integer pageSize){
        //分页
        Page paramsPage = new Page();
        paramsPage.setCurrent(pageNum);
        paramsPage.setSize(pageSize);
        //构建查询
        Wrapper wrapper = new EntityWrapper<Content>();
        if( UtilTool.isNotBlank( name ))
            wrapper.like("title",name);
        if( UtilTool.isNotBlank( type ))
            wrapper.eq("type",type);
        if( UtilTool.isNotBlank( startDate ) ){
            if( UtilTool.isNotBlank( endDate ) && startDate.getTime() == endDate.getTime() ){
                wrapper.between("create_time",startDate,DateUtil.addDays(startDate,1));
            }else{
                wrapper.between("create_time",startDate,
                        UtilTool.isNotBlank(endDate)?DateUtil.addDays(endDate,1):DateUtil.addDays(new Date(),1));
            }
        }

        //去除内衣保养
        wrapper.ne("type","99");

        if( UtilTool.isBlank(startDate) && UtilTool.isNotBlank( endDate )){
            wrapper.le("create_time",DateUtil.addDays(endDate,1));
        }
        //排序
        wrapper.orderBy("create_time",false);
        Page<Content> data = contentService.selectPage(paramsPage,wrapper);
        return new PageResult(0, null, data.getTotal(), data.getRecords());

    }

    /**
     * 新增内容
     * @param content
     * @return
     */
    @PostMapping("addContent")
    public AjaxResult<Boolean> addContent(@RequestBody  Content content ,Authentication authentication){
        if( content == null
                || UtilTool.isBlank( content.getTitle())
                || UtilTool.isBlank( content.getType()))
            return AjaxResult.build(HttpCode.ARGS_ERROR, "请求参数错误!");
        /*if( UtilTool.isNotBlank( content.getUploadImg()) ){
            String imgUrl = BaseCommonUtils.base64ToFile( content.getUploadImg() );//获取上传后返回的图片
            content.setUrl( imgUrl );//上传图片返回路径
        }*/
        content.setCreateTime(new Date());
        if( UtilTool.isNotBlank( content.getType() )){
            Map<Integer,String> authCodeMap  = menuWebService.menuWebAuthCodeMap();
            //加盟政策 + 门店效果 +人才合作 只需要一条记录
            if( authCodeMap.get( content.getType() ).equals(Constants.HE_TYPE_AFFILIATE_POLICY)
                    || authCodeMap.get( content.getType() ).equals(Constants.HE_TYPE_STORE_EFFECT)
                    || authCodeMap.get( content.getType()).equals(Constants.HE_TYPE_PERSONNEL)){
                //查询是否已经存在记录
                Wrapper<Content> queryData = new EntityWrapper<Content>();
                queryData.eq("type", content.getType() );
                Content queryContent = contentService.selectOne(queryData);
                if( UtilTool.isNotBlank( queryContent ))
                    return AjaxResult.build(HttpCode.ARGS_ERROR, "类型数据已存在!");
            }
        }

        //创建人
        SelfUserDetails userDetails = (SelfUserDetails) authentication.getPrincipal();
        content.setCreatePerson( userDetails.getUsername());
        Boolean success = contentService.insert(content);
        return success ? AjaxResult.success() : AjaxResult.build(HttpCode.FAILED, "新增内容信息失败!");
    }

    /**
     * 获取内容信息
     * @param id
     * @return
     */
    @GetMapping("findContent")
    public AjaxResult<Content> findContent( Integer id ){
        if( UtilTool.isBlank( id ))
            return AjaxResult.build(HttpCode.ARGS_ERROR, "请求参数错误!");

        Content content = contentService.selectById( id );
        return AjaxResult.success(content);

    }

    /**
     * 修改内容
     * @param content
     * @return
     */
    @PostMapping("editContent")
    public AjaxResult<Boolean> editContent(@RequestBody Content content){
        if( content == null
                || UtilTool.isBlank( content.getId())
                || UtilTool.isBlank( content.getTitle())
                || UtilTool.isBlank( content.getType()))
            return AjaxResult.build(HttpCode.ARGS_ERROR, "请求参数错误!");

        /*if( UtilTool.isNotBlank( content.getUploadImg()) ){
            String imgUrl = BaseCommonUtils.base64ToFile( content.getUploadImg() );//获取上传后返回的图片
            content.setUrl( imgUrl );//上传图片返回路径
        }*/

        if( UtilTool.isNotBlank( content.getType() ) && UtilTool.isNotBlank( content.getId() )){
            Map<Integer,String> authCodeMap  = menuWebService.menuWebAuthCodeMap();
            //加盟政策 + 门店效果 + 人才合作 只需要一条记录
            if( authCodeMap.get( content.getType() ).equals(Constants.HE_TYPE_AFFILIATE_POLICY)
                    || authCodeMap.get( content.getType() ).equals(Constants.HE_TYPE_STORE_EFFECT)
                    || authCodeMap.get( content.getType()).equals(Constants.HE_TYPE_PERSONNEL)){
                //查询是否已经存在记录
                Wrapper<Content> queryData = new EntityWrapper<Content>();
                queryData.eq("type", content.getType() );
                queryData.ne("id", content.getId() );
                Content queryContent = contentService.selectOne(queryData);
                if( UtilTool.isNotBlank( queryContent ))
                    return AjaxResult.build(HttpCode.ARGS_ERROR, "类型数据已存在!");
            }
        }
        Boolean success = contentService.updateById(content);
        return success ? AjaxResult.success() : AjaxResult.build(HttpCode.FAILED, "修改内容信息失败!");
    }

    /**
     * 根据ID删除内容信息
     * @param id
     * @return
     */
    @PostMapping("delete")
    public AjaxResult<Boolean> delete( Integer id){

        if( UtilTool.isBlank( id ))
            return AjaxResult.build(HttpCode.ARGS_ERROR, "请求参数错误!");

        Boolean success = contentService.deleteById( id );
        return success ? AjaxResult.success() : AjaxResult.build(HttpCode.FAILED, "删除内容信息失败!");
    }

    /**
     * 查询加盟政策
     * @return
     */
    @GetMapping("findContentPolicy")
    public AjaxResult<Content> findContentPolicy(){
        Content content = contentService.findContentPolicy();
        if( UtilTool.isNotBlank( content ))
            return AjaxResult.success(content);
        return AjaxResult.build(HttpCode.FAILED, "查询加盟政策信息失败!");
    }

    /**
     * 查询门店效果
     * @return
     */
    @GetMapping("findContentStoreEffect")
    public AjaxResult<Content> findContentStoreEffect(){
        Content content = contentService.findContentStoreEffect();
        if( UtilTool.isNotBlank( content ))
            return AjaxResult.success(content);
        return AjaxResult.build(HttpCode.FAILED, "查询门店效果信息失败!");
    }

    /**
     * 查询人才合作
     * @return
     */
    @GetMapping("findContentPersonRecruit")
    public AjaxResult<Content> findContentPersonRecruit(){
        Content content = contentService.findContentPersonRecruit();
        if( UtilTool.isNotBlank( content ))
            return AjaxResult.success(content);
        return AjaxResult.build(HttpCode.FAILED, "查询人才合作信息失败!");
    }


    /**
     * 查询内衣保养
     * @return
     */
    @GetMapping("findContentMainTain")
    public AjaxResult<Content> findContentMainTain(){
        Wrapper query = new EntityWrapper();
        query.eq("type","99");
        Content content = contentService.selectOne(query);
        if( UtilTool.isNotBlank( content ))
            return AjaxResult.success(content);
        return AjaxResult.build(HttpCode.FAILED, "查询内衣保养信息失败!");
    }

    /**
     * 修改内衣保养信息
     * @param content 浮动广告URL
     * @return
     */
    @PostMapping("updateMainTainContent")
    public AjaxResult<Boolean> updateMainTainContent(@RequestBody Content content){
        if( UtilTool.isBlank( content.getUrl() ) || UtilTool.isBlank( content.getContentText() ))
            return AjaxResult.build(HttpCode.ARGS_ERROR, "请求参数错误!");
        Wrapper query = new EntityWrapper();
        query.eq("type","99");
        Content contentOld = contentService.selectOne(query);
        if( UtilTool.isBlank( contentOld ))
            return AjaxResult.build(HttpCode.ARGS_ERROR, "查询内衣保养信息失败!");
        contentOld.setUrl(content.getUrl());
        contentOld.setContentText( content.getContentText() );
        boolean success = contentService.updateById( contentOld );
        return success ? AjaxResult.success() : AjaxResult.build(HttpCode.FAILED, "保存内衣保养失败!");
    }

}
